/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/maximum-subtree
   @Language: C++
   @Datetime: 19-04-08 13:24
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
	int dfs(TreeNode *root, TreeNode **node, int &maxsum){
		if(root==NULL) return 0;
		int sum=dfs(root->left,node,maxsum)+dfs(root->right,node,maxsum)+root->val;
		if(sum>maxsum){
			*node=root;
			maxsum=sum;
		}
		return sum;
	}
public:
	/**
	 * @param root: the root of binary tree
	 * @return: the maximum weight node
	 */
	TreeNode * findSubtree(TreeNode * root) {
		// write your code here
		TreeNode *node=NULL;
		int sum=INT_MIN;
		dfs(root,&node,sum);
		return node;
	}
};
